package com.showworkflow.service;

import com.showworkflow.entity.FileHistory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class FileStorageService {

    private final Path fileStorageLocation;
    private final Map<String, List<FileHistory>> fileHistoryMap = new ConcurrentHashMap<>();
    private final DateTimeFormatter timestampFormatter = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss");
    private final Map<String, String> sessionTimestamps = new ConcurrentHashMap<>();

    private String getOrCreateSessionTimestamp(String sessionId) {
        return sessionTimestamps.computeIfAbsent(sessionId, 
            k -> LocalDateTime.now().format(timestampFormatter));
    }

    @Autowired
    public FileStorageService() {
        // 获取项目根目录的绝对路径
        String rootPath = System.getProperty("user.dir");
        // 如果当前在backend目录下，需要调整路径
        if (rootPath.endsWith("backend")) {
            this.fileStorageLocation = Paths.get(rootPath, "src/main/resources/save");
            try {
                // 确保生成目录存在
                Files.createDirectories(fileStorageLocation);
                Files.createDirectories(Paths.get(rootPath, "src/main/resources/generated"));
            } catch (IOException e) {
                throw new RuntimeException("无法创建生成目录", e);
            }
        } else {
            // 假设在项目根目录
            this.fileStorageLocation = Paths.get(rootPath, "backend/src/main/resources/save");
            try {
                // 确保生成目录存在
                Files.createDirectories(fileStorageLocation);
                Files.createDirectories(Paths.get(rootPath, "backend/src/main/resources/generated"));
            } catch (IOException e) {
                throw new RuntimeException("无法创建生成目录", e);
            }
        }
    }

    /**
     * 存储上传的Word文档
     * @param files 上传的Word文档数组
     * @param sessionId 会话ID
     * @return 包含原始文件路径的Map
     * @throws IOException 文件读写异常
     */
    public Map<String, Object> storeFiles(MultipartFile[] files, String sessionId) throws IOException {
        // 使用固定时间戳确保同一会话的文件存在同一目录
        String timestamp = getOrCreateSessionTimestamp(sessionId);
        Path sessionDir = fileStorageLocation.resolve(sessionId).resolve(timestamp);
        Files.createDirectories(sessionDir);

        Map<String, Object> result = new HashMap<>();
        List<String> originalFilePaths = new ArrayList<>();

        for (MultipartFile file : files) {
            String originalFileName = file.getOriginalFilename();
            if (originalFileName == null || originalFileName.trim().isEmpty()) {
                originalFileName = "unknown_file_" + System.currentTimeMillis() + ".doc";
            }
            
            // 存储原始文件
            Path originalFilePath = sessionDir.resolve(originalFileName);
            Files.write(originalFilePath, file.getBytes());
            originalFilePaths.add(originalFilePath.toString());
        }

        result.put("originalFiles", originalFilePaths);
        saveFileHistory(sessionId, files, originalFilePaths, timestamp);

        return result;
    }

    /**
     * 保存文件上传历史（仅记录原始文件）
     */
    private void saveFileHistory(String sessionId, MultipartFile[] files, 
                               List<String> originalFilePaths, String timestamp) {
        List<FileHistory> histories = fileHistoryMap.getOrDefault(sessionId, new ArrayList<>());
        
        // 只保留最近3个版本
        if (histories.size() >= 3) {
            histories.remove(0);
        }

        for (int i = 0; i < files.length; i++) {
            FileHistory history = new FileHistory(
                UUID.randomUUID().toString(),
                files[i].getOriginalFilename() != null ? files[i].getOriginalFilename() : "unknown_file",
                originalFilePaths.get(i),
                null,  // Word文件路径设为null
                LocalDateTime.now(),
                histories.size() + 1
            );
            histories.add(history);
        }

        fileHistoryMap.put(sessionId, histories);
    }

    /**
     * 获取指定会话的文件历史
     */
    public List<FileHistory> getFileHistories(String sessionId) {
        return fileHistoryMap.getOrDefault(sessionId, Collections.emptyList());
    }

    /**
     * 获取单个文件历史记录
     */
    public FileHistory getFileHistory(String sessionId, String fileId) {
        return fileHistoryMap.getOrDefault(sessionId, Collections.emptyList())
                .stream()
                .filter(history -> history.getId().equals(fileId))
                .findFirst()
                .orElse(null);
    }

    /**
     * 获取文件内容
     */
    public byte[] getFileContent(String filePath) throws IOException {
        return Files.readAllBytes(Paths.get(filePath));
    }

    /**
     * 处理两个Word文档
     * @param files 上传的Word文档数组(必须包含2个文件)
     * @param sessionId 会话ID
     * @return 包含处理结果的Map
     * @throws IOException 文件读写异常
     */
    public Map<String, Object> processFiles(MultipartFile[] files, String sessionId) throws IOException {
        if (files == null || files.length != 2) {
            throw new IllegalArgumentException("必须上传2个Word文档");
        }

        // 1. 存储原始文件
        Map<String, Object> result = storeFiles(files, sessionId);
        
        // 2. 添加处理结果
        result.put("processed", true);
        result.put("message", "文件处理完成");
        
        return result;
    }
}
    